// 路由中对应的层
import { pathToRegexp } from "path-to-regexp";
function Layer(path, handler) {
  this.path = path; // path可能是一个查询串
  this.handler = handler;

  const { keys, regexp } = pathToRegexp(path);
  this.regExpPath = regexp;
  this.keys = keys;
}
// 路由 、 中间件
Layer.prototype.match = function (path) {
  if (this.path === path) {
    return true;
  }

  if (this.route) {
    // 路由
    // http://localhost:3000/user/1/2/add
    let matches = path.match(this.regExpPath);

    if (matches) {
      let [, ...values] = matches;
      this.params = this.keys.reduce((memo, current, index) => {
        memo[current.name] = values[index];
        return memo;
      }, {});
      return true;
    }
  }

  if (!this.route) {
    // 中间件
    if (this.path === "/") {
      // 中间件是/都能匹配
      return true;
    }
    return path.startsWith(this.path + "/");
  }
  return false;
};

Layer.prototype.handle_request = function (req, res, next) {
  return this.handler(req, res, next);
};
export default Layer;
